
<?php


	// This class is used to encrypt / decrypt data (usually text)
	// A folder named keys is required and it must contain the public (.pem) and private (.key) keys for encryption and decryption
	
	// You can use the following linux commands for generating a private key:
	//		openssl genrsa -out private.key 1024
	// And these for generating a public key from the private key generated before:
	//		openssl rsa -in private.key -out public.pem -outform PEM -pubout
	// You may have to add the .pem extension to the public key
	
	
	// This encrypts some data passed as argument
	class encryption
	{
		// This encrypts some data using a public key
		// Returns an array containing at [0] the encrypted data, and in [1] the encrypted key
		function encrypt($data)
		{
			// Load the public key into an array
			$public_keys[] = openssl_get_publickey(file_get_contents('keys/public.pem', true));

			// Encrypt the $data and return the $encrypted_data and the $encrypted_keys
			$result = openssl_seal($data, $encrypted_data, $encrypted_keys, $public_keys);
				
			$enc[0] = base64_encode($encrypted_data);
			$enc[1] = base64_encode($encrypted_keys[0]);
			
			// Output the encrypted results
			return $enc;
		}
		
		// This decrypts some data using the files created by the encrypt method
		// Returns the decrypted data from the encrypted data and the encryted keys that must be passed as parameters
		function decrypt($enc_data, $enc_key)
		{
			// Load the private key from the private.key file
			$private_key = openssl_get_privatekey(file_get_contents('keys/private.key', true));

			// Decrypt the data with our $private_key and store the result in $dec_data
			$result = openssl_open(base64_decode($enc_data), $dec_data, base64_decode($enc_key), $private_key);

			// Output the results
			return $dec_data;
			
		}
		
	}

?>